<!-- ArticleEdit.vue -->
<template>
  <div class="article-edit">
    <div class="header">
      <el-button @click="router.back()">返回</el-button>
      <div class="actions">
        <el-button @click="handleSaveAsDraft" :loading="loading">保存草稿</el-button>
        <el-button type="primary" @click="handlePublish" :loading="loading">发布</el-button>
      </div>
    </div>

    <el-form 
      :model="formData" 
      :rules="rules"
      ref="formRef"
      label-width="80px" 
      class="edit-form"
    >
      <el-form-item label="标题" prop="title">
        <el-input v-model="formData.title" placeholder="请输入文章标题" />
      </el-form-item>

      <el-form-item label="摘要" prop="summary">
        <el-input
          v-model="formData.summary"
          type="textarea"
          rows="3"
          placeholder="请输入文章摘要"
        />
      </el-form-item>

      <el-form-item label="封面图">
        <el-upload
          class="cover-uploader"
          :auto-upload="false"
          :show-file-list="false"
          :on-change="handleCoverChange"
          :before-upload="beforeCoverUpload"
        >
          <img v-if="formData.coverImage" :src="formData.coverImage" class="cover-image">
          <el-icon v-else class="cover-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>

      <el-form-item label="内容" prop="content" class="editor-container">
        <div style="border: 1px solid #ccc">
          <Toolbar
            style="border-bottom: 1px solid #ccc"
            :editor="editorRef"
            :defaultConfig="toolbarConfig"
            mode="default"
          />
          <Editor
            style="height: 500px"
            v-model="formData.content"
            :defaultConfig="editorConfig"
            mode="default"
            @onCreated="handleEditorCreated"
          />
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, shallowRef, onBeforeUnmount, onMounted, reactive } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { Plus } from '@element-plus/icons-vue';
import { useArticleStore } from '../store/article';
import { uploadArticleCover } from '../api';
import { storeToRefs } from 'pinia';
import type { FormInstance, FormRules, UploadProps, UploadFile } from 'element-plus';
import type { CreateArticleDTO, ArticleStatus } from '../types/article';
import '@wangeditor/editor/dist/css/style.css';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import type { IDomEditor, IEditorConfig, IToolbarConfig } from '@wangeditor/editor';

const route = useRoute();
const router = useRouter();
const articleStore = useArticleStore();
const { loading } = storeToRefs(articleStore);

const formRef = ref<FormInstance>();
const formData = reactive<CreateArticleDTO>({
  title: '',
  content: '',
  summary: '',
  coverImage: '',
  status: 0, // 草稿状态
});

const rules = reactive<FormRules>({
  title: [
    { required: true, message: '请输入文章标题', trigger: 'blur' },
    { min: 2, max: 100, message: '标题长度应在 2 到 100 个字符之间', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入文章内容', trigger: 'blur' }
  ]
});

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef<IDomEditor>();

// 工具栏配置
const toolbarConfig: Partial<IToolbarConfig> = {
  excludeKeys: []
};

// 编辑器配置
const editorConfig: Partial<IEditorConfig> = {
  placeholder: '请输入内容...',
  MENU_CONF: {}
};

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

const handleEditorCreated = (editor: IDomEditor) => {
  editorRef.value = editor;
};

// 如果是编辑模式，获取文章数据
onMounted(async () => {
  const id = route.params.id as string;
  if (id) {
    await articleStore.fetchArticleById(id);
    const article = articleStore.currentArticle;
    if (article) {
      Object.assign(formData, {
        title: article.title,
        summary: article.summary || '',
        content: article.content,
        coverImage: article.coverImage || '',
        status: article.status,
      });
    }
  }
});

const beforeCoverUpload: UploadProps['beforeUpload'] = (file) => {
  const isImage = file.type.startsWith('image/');
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isImage) {
    ElMessage.error('只能上传图片文件！');
    return false;
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB！');
    return false;
  }
  return true;
};

const convertToBase64 = (file: File): Promise<string> => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result as string);
    reader.onerror = error => reject(error);
  });
};

const handleCoverChange = async (file: UploadFile) => {
  if (!file.raw) return;
  try {
    const base64 = await convertToBase64(file.raw);
    formData.coverImage = base64;
  } catch (error) {
    console.error('转换图片失败:', error);
    ElMessage.error('图片处理失败，请重试');
  }
};

const saveArticle = async (status: ArticleStatus): Promise<void> => {
  if (!formRef.value) return;
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const id = route.params.id as string;
        const articleData = {
          ...formData,
          status,
        };

        if (id) {
          await articleStore.updateArticle(id, articleData);
        } else {
          await articleStore.createArticle(articleData);
        }
        router.push('/admin');
      } catch (error) {
        console.error('保存文章失败:', error);
      }
    }
  });
};

const handleSaveAsDraft = () => saveArticle(0); // 保存为草稿
const handlePublish = () => saveArticle(1); // 发布文章
</script>

<style scoped>
.article-edit {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.actions {
  display: flex;
  gap: 10px;
}

.edit-form {
  max-width: 1000px;
}

.editor-container {
  margin-top: 20px;
}

.cover-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.cover-uploader:hover {
  border-color: #409EFF;
}

.cover-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  display: flex;
  justify-content: center;
  align-items: center;
}

.cover-image {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: cover;
}
</style>